1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.escape;
18
19 import static com.google.common.base.Preconditions.checkNotNull;
20
21 import com.google.common.annotations.Beta;
22 import com.google.common.annotations.GwtCompatible;
23
24 import java.util.HashMap;
25 import java.util.Map;
26
27
28
29
30
31
32
33
34
35
36 @Beta
37 @GwtCompatible
38 public final class CharEscaperBuilder {
39
40
41
42
43 private static class CharArrayDecorator extends CharEscaper {
44 private final char[][] replacements;
45 private final int replaceLength;
46
47 CharArrayDecorator(char[][] replacements) {
48 this.replacements = replacements;
49 this.replaceLength = replacements.length;
50 }
51
52
53
54
55
56 @Override public String escape(String s) {
57 int slen = s.length();
58 for (int index = 0; index < slen; index++) {
59 char c = s.charAt(index);
60 if (c < replacements.length && replacements[c] != null) {
61 return escapeSlow(s, index);
62 }
63 }
64 return s;
65 }
66
67 @Override protected char[] escape(char c) {
68 return c < replaceLength ? replacements[c] : null;
69 }
70 }
71
72
73 private final Map<Character, String> map;
74
75
76 private int max = -1;
77
78
79
80
81 public CharEscaperBuilder() {
82 this.map = new HashMap<Character, String>();
83 }
84
85
86
87
88 public CharEscaperBuilder addEscape(char c, String r) {
89 map.put(c, checkNotNull(r));
90 if (c > max) {
91 max = c;
92 }
93 return this;
94 }
95
96
97
98
99 public CharEscaperBuilder addEscapes(char[] cs, String r) {
100 checkNotNull(r);
101 for (char c : cs) {
102 addEscape(c, r);
103 }
104 return this;
105 }
106
107
108
109
110
111
112
113
114 public char[][] toArray() {
115 char[][] result = new char[max + 1][];
116 for (Map.Entry<Character, String> entry : map.entrySet()) {
117 result[entry.getKey()] = entry.getValue().toCharArray();
118 }
119 return result;
120 }
121
122
123
124
125
126
127
128 public Escaper toEscaper() {
129 return new CharArrayDecorator(toArray());
130 }
131 }